<?php

namespace backend\services\order;

use backend\extensions\ApiBaseService;
use common\models\order\OrderRefundModel;
use common\services\order\OrderRefundCommonService;
use api\services\wechat\MiniPayService;
use common\models\order\OrderModel;
use backend\models\config\AdminUser;
use common\tools\Util;

/**
 * Desc 订单管理服务类
 * @author WMX
 */
class OrderRefundService extends ApiBaseService
{

    /**
     * 列表——获取订单
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['state']) {
            $condition[] = ['=', 'o.state', $params['state'] ?? ''];
        }
        if ($params['order_sn']) {
            $condition[] = ['like', 'o.order_sn', $params['order_sn'] ?? ''];
        }
        if ($params['refund_sn']) {
            $condition[] = ['like', 'o.refund_sn', $params['pay'] ?? ''];
        }
        if ($params['phone']) {
            $condition[] = ['=', 'u.phone', $params['phone'] ?? ''];
        }
        if ($params['time_range']) {
            $condition[] = ['>=', 'o.create_time', $params['time_range'][0] ?? ''];
            $condition[] = ['<', 'o.create_time', $params['time_range'][1] ?? ''];
        }

        $list = OrderRefundCommonService::getUnionAll($condition, $params['page'], $params['page_size']);
        return $list;
    }

    // 获取订单详情
    public static function detail($params)
    {
        $data = OrderRefundCommonService::getOrderDetail($params['refund_sn']);
        return $data;
    }

    // 审核 —— 退款成功——生成销货退款单——完成入库
    public static function check($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $admin = AdminUser::getDataByToken();
            $refund = OrderRefundModel::findOne(['refund_sn' => $params['refund_sn']]);
            if (empty($refund)) {
                throw new \Exception('订单信息异常');
            }
            if ($refund['state'] != OrderRefundModel::STATE_WAIT_AUDIT) {
                throw new \Exception('该订单状态无法操作');
            }
            $order_info = OrderModel::findOne(['order_sn' => $refund['order_sn']]);
            //通过_修改退款单状态
            $refund->state = 2;
            $refund->examine_id = $admin['id'];
            $refund->examine_time = date('Y-m-d H:i:s');


            if ($order_info['pay_way'] == 1 || $order_info['pay_way'] == 2) {
                $refund_res =  MiniPayService::refund($refund);
                if ($refund_res['code'] != 0) {
                    throw new \Exception($refund_res['message']);
                }
            } elseif ($order_info['pay_way'] == 4) {
                // 余额支付退款_用户金额回滚
                list($code, $msg) = OrderRefundCommonService::refund($refund);
                if ($code == 1) {
                    throw new \Exception($msg);
                }
            }


            $refund->refund_time = date('Y-m-d H:i:s');
            if (empty($refund->save())) {
                throw new \Exception('退款异常2');
            }
            // 其他业务处理
            $res = self::other($refund);
            if ($res['code'] == 1) {
                throw new \Exception('退款异常3');
            }

            //取消券回滚
            if ($order_info['coupon_amount'] > 0) {
                \api\services\active\ActiveCouponService::rollback($order_info['order_sn']);
            }


            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }


    // 退款之后业务处理
    public static function other($refund)
    {
        try {
            // 修改订单状态
            OrderModel::updateData(['state' => OrderModel::STATE_REFUND, 'refund_time' => date('Y-m-d H:i:s')], ['order_sn' => $refund['order_sn']]);
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }


    // 申请退款
    /**
     * 申请退款
     * @param array $params 参数
     * **/
    public static function apply($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $admin = AdminUser::getDataByToken();

            $type = 1;
            $name = $params['mobile'];
            $mobile = $params['mobile'];
            $reason = $params['reason'] ?? '';


            $order = OrderModel::getDataOne([
                'order_sn' => $params['order_sn'],
            ]);
            if (empty($order)) {
                return self::jsonError('订单信息异常，请检查');
            }
            if (in_array($order['state'], [
                OrderModel::STATE_WAIT_PAY,
                OrderModel::STATE_CANCEL
            ])) {
                return self::jsonError('订单' . (OrderModel::$state[$order['state']] ?: '状态不可申请退款'));
            }

            $info = OrderRefundModel::getDataOne(['order_sn' => $order['order_sn']]);
            if (!empty($info)) {
                $ready_goods = json_decode($info['goods'], true);
                $state = false;
                // 判断商品是否已经被退款过
                foreach ($params['goods'] as $apply_goods) {
                    foreach ($ready_goods as $rgoods) {
                        if ($rgoods['gid'] == $apply_goods['gid'] && $rgoods['count'] >= $apply_goods['count']) {
                            $state = true;
                            break;
                        }
                    }
                }

                if ($state) {
                    return self::jsonError('部分商品已退款，数据异常');
                }
            }

            $refund_sn = Util::createSn('tk');
            $data = [
                'user_id' => $order['user_id'],
                'refund_sn' => $refund_sn,
                'order_sn' => $order['order_sn'],
                'type' => $type,
                'state' => OrderRefundModel::STATE_WAIT_AUDIT,
                'apply_amount' => $params['refund_money'],         // 申请金额
                'refund_amount' => $params['refund_money'],         // 实退金额
                'name' => $name,
                'mobile' => $mobile,
                'goods' => json_encode($params['goods']),
                'reason' => $reason,
                'create_time' => date('Y-m-d H:i:s'),
            ];
            OrderRefundModel::create($data);
            OrderModel::updateData(['state' => OrderModel::STATE_REFUNDING, 'refund_time' => date('Y-m-d H:i:s')], ['order_sn' => $order['order_sn']]);
            $transaction->commit();
            return self::jsonSuccess(['refund_sn' => $refund_sn]);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError('申请退款失败');
        }
    }
}
